package com.yykj.drup.server.controller;

import com.google.gson.Gson;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.SubscribePushParamResp;
import com.kuaidi100.sdk.response.SubscribePushResult;
import com.kuaidi100.sdk.response.SubscribeResp;
import com.kuaidi100.sdk.utils.SignUtils;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.vo.ResultVO;
import com.yykj.drup.server.config.KuaiDiAccountConfig;
import com.yykj.drup.server.form.SubscribePollFrom;
import com.yykj.drup.server.model.ExpressContext;
import com.yykj.drup.server.model.OrderInfo;
import com.yykj.drup.server.service.ExpressContextService;
import com.yykj.drup.server.service.ExpressService;
import com.yykj.drup.server.service.OrderInfoService;
import com.yykj.prescription.client.feign.PrescriptionFeignClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author zeng
 * @Date 2022/3/29
 */
@Api(tags = "物流信息管理")
@RequestMapping("/api/drug/")
@AllArgsConstructor
@RestController
@Slf4j
public class ExpressController {

    final PrescriptionFeignClient prescriptionFeignClient;
    final ExpressService expressService;
    final ExpressContextService expressContextService;
    final OrderInfoService orderInfoService;

   /* @Deprecated
    @ApiOperation("根据订单主键ID查询物流信息")
    @PostMapping(value = "/express/seachExpressPoll")
    public ResultVO<QueryTrackData> seachPoll(Integer orderId){
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null){
            return ResultVO.error("订单不存在");
        }
        List<QueryTrackData> queryTrackData = expressService.pollKuaidi(orderInfo.getOrderCom(), orderInfo.getOrderComNumber());
        return ResultVO.success(queryTrackData);

    }*/

    @Deprecated
    @ApiOperation("根据物流单号查询实时物流信息")
    @GetMapping(value = "/express/number")
    @ApiImplicitParam(name = "orderComNumber",value = "药店订单物流单号",required = true)
    public ResultVO<QueryTrackData> seachPoll(String orderComNumber){
        List<QueryTrackData> queryTrackData = expressService.pollKuaidi("", orderComNumber);
        return ResultVO.success(queryTrackData);
    }

    @ApiOperation("根据物流单号查询系统物流信息")
    @GetMapping(value = "/express/orderComNumber")
    @ApiImplicitParam(name = "orderComNumber",value = "药店订单物流单号",required = true)
    public ResultVO<ExpressContext> orderComNumber(@RequestParam("orderComNumber") String orderComNumber){
        return ResultVO.success(expressContextService.findContextsByOrderComNumber(orderComNumber));
    }

    @Deprecated
    @ApiOperation("订阅")
    @PostMapping(value = "/express/poll")
    public SubscribeResp poll(@RequestBody SubscribePollFrom from){
        HttpResult httpResult = expressService.expressPoll(from.getNumber(), from.getPhone(), from.getCompany());
        if (httpResult.getStatus() == HttpStatus.SC_OK && StringUtils.isNotBlank(httpResult.getBody())){
            return new Gson().fromJson(httpResult.getBody(), SubscribeResp.class);
        }
        return null;
    }


    @ApiOperation("确认收货")
    @ApiImplicitParam(name = "id",value = "药店订单主键ID",required = true)
    @GetMapping("/productPayOrder/orderStoreNum")
    public ResultVO orderStoreNum(@RequestParam("id") Integer id){
        OrderInfo orderInfo = orderInfoService.getById(id);
        if (orderInfo == null){
            return ResultVO.error(ResultEnums.NOT_EXIST);
        }
        Boolean check = orderInfoService.setOrderInfoCheck(id);
        if (check){
            //更新系统总订单状态
            orderInfoService.setOrderStatusOK(orderInfo.getOrderSysNum());
        }
        return ResultVO.success(check);
    }
    @ApiIgnore
    @ApiOperation("物流信息回调(临时)")
    @PostMapping(value = "/express/callback")
    public SubscribeResp callback() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        System.out.println("物流信息回调(临时).........................{}"+ request.getParameter("param"));
        SubscribeResp subscribeResp = new SubscribeResp();
        subscribeResp.setResult(Boolean.TRUE);
        subscribeResp.setReturnCode("200");
        subscribeResp.setMessage("成功");
        return subscribeResp;
    }
    @Deprecated
    @ApiOperation("物流信息回调")
    @PostMapping(value = "/express/callBackUrl")
    public SubscribeResp callBackUrl() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        System.out.println("物流信息回调.........................");
        log.info("快递100订阅推送回调开始。。。。。。");
        String param = request.getParameter("param");
        String sign = request.getParameter("sign");
        //建议记录一下这个回调的内容，方便出问题后双方排查问题
        log.info("快递100订阅推送回调结果|{}|{}",param,sign);
        //订阅时传的salt,没有可以忽略
        String salt = KuaiDiAccountConfig.userid;
        String ourSign = SignUtils.sign(param + salt);
        log.info("产生ourSign{}",ourSign);
        SubscribeResp subscribeResp = new SubscribeResp();
        subscribeResp.setResult(Boolean.TRUE);
        subscribeResp.setReturnCode("200");
        subscribeResp.setMessage("成功");
        //加密如果相等，属于快递100推送；否则可以忽略掉当前请求
        log.info("传过来的sign{}",sign);
        if (ourSign.equals(sign)){
            log.info("签名验证通过开始业务处理");
            SubscribePushParamResp subscribePushParamResp = new Gson().fromJson(param, SubscribePushParamResp.class);
            log.info("快递100订阅推送信息{}",subscribePushParamResp.getLastResult());
            SubscribePushResult lastResult = subscribePushParamResp.getLastResult();
            if ("1".equals(lastResult.getIscheck())){
                log.info("已验证签名更改订单物流签收信息");
                //更新药店订单物流签收状态
                Boolean check = orderInfoService.setOrderInfoComCheck(lastResult.getNu(),lastResult.getIscheck());
                log.info("已验证签名更改订单物流签收信息结果{}",check);
            }
            //插入药店订单物流信息
            log.info("插入药店订单物流信息{}",lastResult);
            expressService.insertExpressContext(lastResult);
            return subscribeResp;
        }
        return null;
    }
/**
 * 快递100订阅推送回调开始。。。。。。
 * 快递100订阅推送回调结果|
 * {
 * "status":"polling",
 * "billstatus":"change",
 * "message":"变化",
 * "autoCheck":"0",
 * "comOld":"",
 * "comNew":"",
 * "lastResult":{
 *      "message":"ok",
 *      "nu":"9887024189028",
 *      "ischeck":"0",
 *      "condition":"F00",
 *      "com":"youzhengguonei",
 *      "status":"200",
 *      "state":"0",
 *      "data":[
 *                  {"time":"2022-03-30 00:11:15","ftime":"2022-03-30 00:11:15","context":"北京市北京市|处理中心封车|离开【北京综合邮件处理中心】,下一站【南京邮区中心局邮件处理中心】"},
 *                  {"time":"2022-03-28 19:21:45","ftime":"2022-03-28 19:21:45","context":"北京市北京市|收寄计费信息|【北京市大兴区兴华路邮政支局大宗组】已收寄,揽投员:韩铭腾,电话:18511858190"}
 *              ]
 *            }
 * }|null
 * 快递100订阅推送回调开始。。。。。。
 * 快递100订阅推送回调结果|{"status":"polling","billstatus":"got","message":"寄件","autoCheck":"0","comOld":"","comNew":"","lastResult":{"message":"ok","nu":"9887024189028","ischeck":"0","condition":"F00","com":"youzhengguonei","status":"200","state":"1","data":[{"time":"2022-03-28 19:21:45","ftime":"2022-03-28 19:21:45","context":"北京市北京市|收寄计费信息|【北京市大兴区兴华路邮政支局大宗组】已收寄,揽投员:韩铭腾,电话:18511858190"}]}}|null
 */

}
